
import * as test from "@/axios/test.js";
import * as webman from "@/axios/webman.js";

// import * as audioUtils from "./audio2.js";
import * as utils from "./util";


let intervalId;


function startSTTWS ()
{
  const audioPlayer = new AudioPlayer("/ttsutil");
  audioPlayer.onPlay = () => {
     // 每隔一段时间检查一次播放进度
    intervalId = setInterval(() => {
      console.log(audioPlayer.audioContext.currentTime);
    }, 30);




  };
  audioPlayer.onStop = (audioDatas) => {
    console.log(audioDatas);
    if(intervalId)
    {
      clearInterval(intervalId);
    }

  };

  console.log(audioPlayer);



// webman.tts({
//   // "appkey":"MRial6V9i3C6vA2I",
//   "text":"你好啊，小飞",
//   // "token":"a937efa817444169bd2627a2a55bb630",
//   // "format":"wav"
// })
// .then(response => response.blob())  // 将响应转换为Blob对象
// .then(blob => {
//     // 创建Blob URL
//     const url = URL.createObjectURL(blob);
    
//     // 创建下载链接
//     const downloadLink = document.createElement('a');
//     downloadLink.href = url;
//     downloadLink.download = 'downloaded_audio.wav';  // 指定下载文件名
//     // download as link
//     downloadLink.style.display = 'none';
//     document.body.appendChild(downloadLink);
    
//     // 触发下载
//     downloadLink.click();
    
//     // 清理DOM和释放Blob URL
//     document.body.removeChild(downloadLink);
//     URL.revokeObjectURL(url);  // 释放内存中的URL
// })
// .catch(error => {
//   console.error('Error:', error);
// });


// const ttsws = new WebSocket('ws://nls-gateway-cn-shanghai.aliyuncs.com/ws/v1?token=cc1ca3cf9b3949daa8a94d729fd183eb');
const ttsws = new WebSocket('ws://127.0.0.1:8090/tts/?token=123');
// const ttsws = new WebSocket('ws://nls-gateway.aliyuncs.com/ws/v1?token=c79f6e32ebdb445cad25d74611b8b489');
ttsws.binaryType = 'arraybuffer'; 



function generateRandomString(length) {
  const validChars = 'abcdefghijklmnopqrstuvwxyz0123456789';
  let array = new Uint8Array(length);
  window.crypto.getRandomValues(array);
  array = array.map(x => validChars.charCodeAt(x % validChars.length));
  return String.fromCharCode.apply(null, array);
}


function generateHex32() {
  // 创建一个16字节的随机数组
  const array = new Uint8Array(16);
  window.crypto.getRandomValues(array);

  // 将数组中的每个元素转换为十六进制字符串
  const hexString = Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
  return hexString;
}


// 4为随机数

let num = Math.random() * 8999 + 1000;

// let task_id = "640bc797bb684bd69601856533074313";
// let message_id = '05450bf69c53413f8d88aed1e4611234';


let task_id =  generateHex32();


console.log(task_id);

console.log("ttsws");
let session = "";
let audioBase64 = "";
ttsws.onopen = function()
{
  let message_id =  generateHex32();
  let data = {
        "header": {
            "message_id": message_id,
            "task_id": task_id,
            "namespace": "FlowingSpeechSynthesizer",
            "name": "StartSynthesis",
            "appkey": "MRial6V9i3C6vA2I"
        },
        "payload": {
            "voice": "zhibing_emo", // zhibing_emo zhimi_emo
            "format": "wav",
            "sample_rate": 16000,
            "volume": 50,
            "speech_rate": 0,
            "pitch_rate": 0,
            "enable_subtitle":1,
            "enable_phoneme_timestamp":1
        }
    }
    // ttsws.send(JSON.stringify(data));


}

let i = 0;
// let is = ["你","好啊","!","hello 端午节","快乐,","今天天气特别好，我想出去散散心，吃些伊美味的食品"];
let is = ["今天天气特别好，我想出去散散心，吃些伊美味的食品"];
function sendMsg()
{

  setTimeout(() => {
    let message_id =  generateHex32();
    let text = is[i];
    let sendData  =  {
          "header": {
              "message_id": message_id,
              "task_id": task_id,
              "namespace": "FlowingSpeechSynthesizer",
              "name": "RunSynthesis",
              "appkey": "MRial6V9i3C6vA2I",
          },
          "payload": {
              "text": text,
          }
      }
      ttsws.send(JSON.stringify(sendData));
      i++;
      if(i <= is.length-1)
      {
        sendMsg();
      }else{
        let message_id =  generateHex32();
        let endData = {
            "header": {
                "message_id": message_id,
                "task_id": task_id,
                "namespace": "FlowingSpeechSynthesizer",
                "name": "StopSynthesis",
                "appkey": "MRial6V9i3C6vA2I"
            }
        }
        ttsws.send(JSON.stringify(endData));
      }
  }, 10);  
}




let isPlay = false;
ttsws.onmessage = function(event) {

  try{
    let data = JSON.parse(event.data) ;
    if(data.status)
    {

      if(data.status == "success")
      {
        let message_id =  generateHex32();
        let data = {
            "header": {
                "message_id": message_id,
                "task_id": task_id,
                "namespace": "FlowingSpeechSynthesizer",
                "name": "StartSynthesis",
                "appkey": "MRial6V9i3C6vA2I"
            },
            "payload": {
                "voice": "guijie",
                "format": "wav",
                "sample_rate": 16000,
                "volume": 50,
                "speech_rate": 0,
                "pitch_rate": 0,
                "enable_subtitle":true,
                "enable_phoneme_timestamp":true
            }
        }
        ttsws.send(JSON.stringify(data));
      }else if(data.audioUrl)
      {
        ttsws.close();
        const audio = new Audio(data.audioUrl+"?="+Math.random()); // 替换为你的音频文件路径
        audio.play();
        audio.addEventListener('timeupdate', function() {
          console.log(audio.currentTime);
        });
        audio.addEventListener('ended', function() {
          console.log("播放完毕");
        });
      }
     
    }
    
    if(data.header)
    {
  
      let name  = data.header.name;
      switch(name)
      {
        case "SynthesisCompleted":
          ttsws.close();
          break;
        case "SynthesisStarted":
          sendMsg();
      
          break;
      }
    }
  }catch(e) {
    // var float32Array = util.hexToFloat32Array(event.data);
    // utils.getBase64(event.data).then((base64)=>{
    //   console.log(base64);
    // })

    // if(!isPlay)
    // {
    //   audioPlayer.start({
    //     autoPlay: true,
    //     sampleRate: 16000,
    //     resumePlayDuration: 2000
    //   });
    //   audioPlayer.play();
    //   isPlay = true;
    // }

    // console.log(event.data);
    // var view = new Int16Array(event.data);
    // audioPlayer.postMessage({
    //   type: "Int16Array",
    //   data: view,
    //   isLastData: true,
    // });
    return;
    let base64 = utils.hexToBase64(event.data);
    console.log(base64);
    return;
    audioPlayer.postMessage({
      type: "Float32Array",
      data: event.data,
      isLastData: true,
    });
    // audioUtils.receiveAudioData(event.data);
  }
 

  return;
  console.log(data);
  if(data.status == 0)
  {
    if(data.signal == "server ready")
    {
      session = data.session;
    }else if(data.signal == "connection will be closed")
    {
      console.log("合成完毕")
    }
  }
  else if(data.status == 1 &&  data.audio)
  {

    audioBase64 = audioBase64+data.audio;
    // const audio = document.getElementById('audioId');
    // audio.src = `data:audio/wav;base64,${data.audio}`;
    // audio.play().catch(e => console.log("播放失败: " + e.message));

    // console.log(audio.src)
    // playAudio(data.audio)
    // let audioBlob =   base64ToBlob(data.audio,'wav')
    // let audio = document.getElementById("audioId");
    // audio.src = window.URL.createObjectURL(audioBlob);
    // audio.addEventListener("canplay", () => {
    //     window.URL.revokeObjectURL(audio.src);
    // });
    // audio.play();
  }
  else if(data.status == 2)
  {
    let endData = {
      "header": {
          "message_id": "05450bf69c53413f8d88aed1ee60ee60",
          "task_id": "640bc797bb684bd69601856513071307",
          "namespace": "FlowingSpeechSynthesizer",
          "name": "StopSynthesis",
          "appkey": "MRial6V9i3C6vA2I"
      }
  }
    ttsws.send(JSON.stringify(endData));
    playAudio(audioBase64);
    console.log("接收结束")
        // const audio = document.getElementById('audioId');
    // audio.src = `data:audio/wav;base64,${data.audio}`;
    // audio.play().catch(e => console.log("播放失败: " + e.message));
  }
  // const base64Data = event.data;
  // playAudio(base84Data);
}





const audioContext = new (window.AudioContext || window.webkitAudioContext)();

function playAudio(base64String) {
  console.log(base64String);

    // 将Base64字符串解码为二进制数据
    const audioData = base64ToArrayBuffer(base64String);

    // 使用AudioContext解码音频数据
    audioContext.decodeAudioData(audioData, function(buffer) {
        const source = audioContext.createBufferSource(); // 创建一个音频源
        source.buffer = buffer;  // 将解码的音频数据赋值给音频源
        source.connect(audioContext.destination);  // 连接到输出设备
        source.start(0);  // 立即播放
    }, function(e) {
        console.log("Error with decoding audio data :" + e.err);
    });
}

function base64ToArrayBuffer(base64) {
    const binaryString = window.atob('data:audio/wav;base64,'+base64);
    const len = binaryString.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
        bytes[i] = binaryString.charCodeAt(i);
    }
    return bytes.buffer;
}


function base64ToBlob(base64, fileType) {
  let typeHeader = 'data:application/' + fileType + ';base64,'; // 定义base64 头部文件类型
  let audioSrc = typeHeader + base64; // 拼接最终的base64
  let arr = audioSrc.split(',');
  let array = arr[0].match(/:(.*?);/);
  let mime = (array && array.length > 1 ? array[1] : type) || type;
  // 去掉url的头，并转化为byte
  let bytes = window.atob(arr[1]);
  // 处理异常,将ascii码小于0的转换为大于0
  let ab = new ArrayBuffer(bytes.length);
  // 生成视图（直接针对内存）：8位无符号整数，长度1个字节
  let ia = new Uint8Array(ab);
  for (let i = 0; i < bytes.length; i++) {
    ia[i] = bytes.charCodeAt(i);
  }
  return new Blob([ab], {
    type: mime
  });
}
}


export { startSTTWS }
